package com.dly.hope.utils;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ReadConverterContext;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.dly.hope.type.BaseEnum;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.Arrays;

/**
 * @author linyu.dai
 * @project myserve
 * @description
 * @creat 2022/11/4 16:05:00
 */
@Slf4j
public class EnumConverter implements Converter<BaseEnum> {


    @Override
    public WriteCellData<String> convertToExcelData(BaseEnum value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        //枚举类以名字保存
        return new WriteCellData<>(value.getName());
    }

    @Override
    public BaseEnum convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        log.info(cellData.getStringValue());
        //获取字段的类型
        Class<?> type = contentProperty.getField().getType();
        //判断是否是枚举
        if(type.isEnum()){
            //获取枚举的所有数组
            Object[] enumConstants = type.getEnumConstants();
            //判断类型 返回对应的对象
            for (Object o:enumConstants) {
                if(o.toString().equals(cellData.getStringValue())){
                    return (BaseEnum) o;
                }
            }
        }
        return Converter.super.convertToJavaData(cellData, contentProperty, globalConfiguration);
    }
}
